package org.abettor.pushbox.activity2;

import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import org.abettor.pushbox.config.Config;
import org.abettor.pushbox.download.ParaDownloadRetValue;
import org.abettor.pushbox.model.LastTimeIdInterface;
import org.abettor.pushbox.model.SelfMessage;
import org.abettor.pushbox.R;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Toast;

/**
 * 实现列表的Activity
 * 
 * @author jzh
 * 
 */
public abstract class AbstractSendListActivity
		extends Activity {
	private ListView sendList = null;// 显示内容的列表
	private ProgressDialog sendProgressBar;// 进度条对话框
	private boolean isLoading = false;
	protected Handler mHandler = new Handler();
	private int isHasMore;// 判断是否有更多的数据
	protected UserMapAdapter userMapAdapter;// 用户的监听器
	private EditText msgText;// 发送消息的对话框
	private Button sendButton;// 发送按钮
	/**
	 * 非常不优雅的来个方法，方便子类调用onCreate
	 * @param savedInstanceState
	 */
	protected void superOncreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
	}

	/**
	 * 创建的操作
	 */
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.abstract_send_list_activity);
		msgText = (EditText) this.findViewById(R.id.msg);
		sendButton = (Button) this.findViewById(R.id.send_button);
		sendButton.setOnClickListener(new ButtonOnclickListener());
		sendButton.requestFocus();
		sendList = (ListView) this.findViewById(R.id.send_list);// 显示内容的列表
		addFooterView(sendList);
		userMapAdapter = new UserMapAdapter(new LinkedList<LastTimeIdInterface>());
		sendList.setAdapter(userMapAdapter);
		sendList.setOnScrollListener(new MyOnScrollListener());
	}

	/*------------------------------发送消息的操作------------------------*/
	// 按钮点击按钮的监听器
	private class ButtonOnclickListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (v == sendButton) {
				SelfMessage self = Config.readSelfMessage(AbstractSendListActivity.this);
				if(self == null){
					Toast.makeText(
							AbstractSendListActivity.this,
							AbstractSendListActivity.this
									.getText(R.string.abstract_sendlist_activity_setnickfirst),
							Toast.LENGTH_SHORT).show();
					return;
				}
				String content = msgText.getEditableText().toString();
				if (content == null || "".equals(content) || content.trim().length() == 0) {
					Toast.makeText(
							AbstractSendListActivity.this,
							AbstractSendListActivity.this
									.getText(R.string.abstract_sendlist_activity_messagenotnull),
							Toast.LENGTH_SHORT).show();
					return;
				}
				sendMsg(content.trim());
			}
		}
	}

	// 发送消息的操作
	private void sendMsg(final String content) {
		sendProgressBar = new ProgressDialog(this);
		sendProgressBar.setTitle(R.string.abstract_sendlist_activity_sendmsg);
		sendProgressBar.setMessage(this
				.getText(R.string.abstract_sendlist_activity_sendmsg_sending));
		sendProgressBar.show();
		Thread thread = new Thread() {
			@Override
			public void run() {
				boolean flag = sendMsgOperation(content);
				sendProgressBar.dismiss();
				if (flag) {// 发送消息成功
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							loadNewstTList();// 加载最新数据的对话框
							msgText.setText("");// 清空输入框
						}
					});
				} else {// 显示发送消息失败的对话框
					mHandler.post(new Runnable() {
						@Override
						public void run() {
							showSendMsgFailDialog();
						}
					});
				}
			}
		};
		thread.start();
	}

	// 显示发送消息失败的对话框
	private void showSendMsgFailDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		AlertDialog dialog = builder.create();
		dialog.setTitle(this.getText(R.string.msg));
		dialog.setMessage(this
				.getText(R.string.abstract_sendlist_activity_sendmsgfail));
		dialog.setButton(DialogInterface.BUTTON_POSITIVE,
				this.getText(android.R.string.ok),
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
					}
				});
		dialog.show();
	}

	/*------------------------------滚动的监听器--------------------------*/
	private class MyOnScrollListener implements OnScrollListener {
		private boolean linloading = false;
		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
			// 把totalItemCount剔除掉，因为加入footer，所以剔除掉totalItemCount为1的时候
			if (totalItemCount == 1) {
				return;
			}
			if (firstVisibleItem + visibleItemCount >= totalItemCount
					&& isHasMore == ParaDownloadRetValue.HASMORE) {
				if (!linloading) {
					linloading = true;
					loadEarlyList();// 加载数据
					mHandler.postDelayed(new Runnable() {
						@Override
						public void run() {
							linloading = false;
						}
					}, 4000);
				}
				//loadEarlyList();// 加载数据
			}
		}

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
		}
	}

	// 加载数据的操作
	private void loadEarlyList() {
		// 已经加载时地图就不在加载
		if (isLoading) {
			return;
		}
		Thread thread = new Thread() {
			@Override
			public void run() {
				loadEarlyListOperation();
			}
		};
		isLoading = true;
		showEarlyProgressBar();
		thread.start();
	}

	/*------------------------------------------------------------------*/
	// 增加footer view
	private void addFooterView(ListView listView) {
		View localView = LayoutInflater.from(this).inflate(
				R.layout.abstract_send_list_footer, null);
		listView.addFooterView(localView);
	}

	// 加载早期数据数据列表
	private void loadEarlyTList() {
		// 已经加载的就不载操作
		if (isLoading) {
			return;
		}
		Thread thread = new Thread() {
			@Override
			public void run() {
				loadEarlyListOperation();
			}
		};
		isLoading = true;
		showEarlyProgressBar();// 显示加载早期对话框的操作
		thread.start();
	}

	// 加载最新的消息列表
	protected void loadNewstTList() {
		if (isLoading) {
			return;
		}
		Thread thread = new Thread() {
			@Override
			public void run() {
				loadNewstTListOperation();
			}
		};
		isLoading = true;
		showOldProgressBar();// 显示加载最新对话框的操作
		thread.start();
	}

	// 显示较小消息时加载的对话框
	private void showEarlyProgressBar() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				View view = AbstractSendListActivity.this
						.findViewById(R.id.footor);
				view.setVisibility(View.VISIBLE);
			}
		});
	}

	// 使较小消息时消息时对话框
	private void dismissEarlyProgressBar() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				View view = AbstractSendListActivity.this
						.findViewById(R.id.footor);
				view.setVisibility(View.GONE);
			}
		});
	}

	// 加载较新列表的操作
	private void loadNewstTListOperation(){
		Date date = userMapAdapter.getNewTime();
		String content = loadOldStrFromNet(date);
		dimissOldProgressBar();
		isLoading = false;
		//读取内容为空
		if(content == null){
			loadNewFailure();//显示对话框加载错误的对话框
			return;
		}
		//解析数据的列表
		if(userMapAdapter.isEmpty()){//当列表中的数据为空时,需要解析一下是否还有更多数据，有了就算了
			isHasMore = isHasMoreResult(content);
			if (isHasMore == ParaDownloadRetValue.ERROR) {// 解析数据失败
				loadNewFailure();
				return;
			}
		}
		//解析数据的列表
		final List<LastTimeIdInterface> reList = pareMoreResult(content);
		if (reList == null) {
			loadNewFailure();// 显示加载失败的对话框
			return;
		}
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				userMapAdapter.addTList(reList);
				userMapAdapter.notifyDataSetChanged();
			}
		});
		showListMapView();
	}

	// 加载较早消息列表的操作
	private void loadEarlyListOperation() {
		Date date = userMapAdapter.getLastAccessTime();
		String content = loadEarlyStrFromNet(date);
		dismissEarlyProgressBar();
		isLoading = false;
		// 读取内容为空
		if (content == null) {
			loadEarlyFailure();// 显示对话框加载错误的对话框
			return;
		}
		// 判断是否有更多的数据
		isHasMore = isHasMoreResult(content);
		if (isHasMore == ParaDownloadRetValue.ERROR) {// 解析数据失败
			loadEarlyFailure();
			return;
		}
		// 解析数据的列表
		final List<LastTimeIdInterface> reList = pareMoreResult(content);
		if (reList == null) {
			loadEarlyFailure();// 显示加载失败的对话框
			return;
		}
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				userMapAdapter.addTList(reList);
				userMapAdapter.notifyDataSetChanged();
			}
		});
		// 显示用户的对话框
		showListMapView();
	}

	// show List View
	private void showListMapView() {
		mHandler.post(new Runnable() {
			@Override
			public void run() {
				if (AbstractSendListActivity.this.sendList.getVisibility() == View.GONE) {
					AbstractSendListActivity.this.sendList
							.setVisibility(View.VISIBLE);
				}
			}
		});
	}

	// 显示加载较早内容失败的对话框
	private void loadEarlyFailure() {
		mHandler.post(new LoadFailureRunnable() {
			@Override
			public void loadMap() {
				// 进行回调较早函数的操作
				loadEarlyTList();
			}
		});
	}

	// 显示加载较晚内容的对话框
	private void loadNewFailure() {
		mHandler.post(new LoadFailureRunnable() {
			@Override
			public void loadMap() {
				//进行较新消息的回调操作
				loadNewstTList();
			}

		});
	}

	/*-----------------------------------------------------------------------------------*/
	/**
	 * 是否有更多的记录
	 */
	protected abstract int isHasMoreResult(String content);

	/**
	 * 解析记录的条数
	 * 
	 * @param content
	 * @return
	 */
	protected abstract List<LastTimeIdInterface> pareMoreResult(String content);

	/**
	 * 从网络上加载较早字符串
	 */
	protected abstract String loadEarlyStrFromNet(Date date);

	/**
	 * 从网络上加载最新的字符串
	 * 
	 * @return
	 */
	protected abstract String loadOldStrFromNet(Date date);

	/**
	 * 显示加载最新对话框
	 */
	protected abstract void showOldProgressBar();

	/**
	 * 把加载最新对话框
	 */
	protected abstract void dimissOldProgressBar();

	/**
	 * 获得list列表的view
	 */
	protected abstract View getListView(int position, View convertView,
			ViewGroup parent,LastTimeIdInterface bean);

	/**
	 * 发送消息的操作
	 * 
	 * @param msg
	 * @return
	 */
	protected abstract boolean sendMsgOperation(String msg);

	/*---------------------------------list adapter开始-------------------------------------*/
	// 通用的adapter
	protected class UserMapAdapter extends
			BaseAdapter {
		protected List<LastTimeIdInterface> netTList;// 显示的列表

		// 获得最后一次运行时间
		public Date getLastAccessTime() {
			if (netTList == null || netTList.isEmpty()) {
				return null;
			}
			int size = netTList.size();
			LastTimeIdInterface t = null;
			synchronized (netTList) {
				t = netTList.get(size - 1);
			}
			return t.getTime();
		}

		/**
		 * 获得最新运行的时间
		 * 
		 * @return
		 */
		public Date getNewTime() {
			if (netTList == null || netTList.isEmpty()) {
				return null;
			}
			LastTimeIdInterface t = null;
			synchronized (netTList) {
				t = netTList.get(0);
			}
			return t.getTime();
		}

		/**
		 * 向列表中加入数据
		 */
		public void addTList(List<LastTimeIdInterface> toAddList) {
			if (toAddList == null) {
				return;
			}
			Date lastTime = getLastAccessTime();
			Iterator<LastTimeIdInterface> itr = toAddList.iterator();
			while (itr.hasNext()) {
				LastTimeIdInterface t = itr.next();
				if (lastTime == null || t.getTime().before(lastTime)) {
					netTList.add(t);
				} else {
					netTList.add(0, t);
				}
			}
		}

		/**
		 * 向列表头加入数据
		 * 
		 * @param toAddList
		 */
		public void addTListFirst(List<LastTimeIdInterface> toAddList) {
			if (toAddList == null) {
				return;
			}
			Collections.reverse(toAddList);
			synchronized (netTList) {
				for (LastTimeIdInterface t : toAddList) {
					netTList.add(0, t);
				}
			}
		}

		/**
		 * 清空数据
		 */
		public void clearTList() {
			synchronized (netTList) {
				netTList.clear();
			}
		}

		/**
		 * 构造函数
		 */
		public UserMapAdapter(List<LastTimeIdInterface> list) {
			this.netTList = list;
		}

		@Override
		public int getCount() {
			synchronized (netTList) {
				return netTList.size();
			}
		}

		@Override
		public Object getItem(int position) {
			synchronized (netTList) {
				return netTList.get(position);
			}
		}

		@Override
		public long getItemId(int position) {
			synchronized (netTList) {
				return netTList.get(position).getId();
			}
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LastTimeIdInterface bean = netTList.get(position);
			return getListView(position, convertView, parent, bean);
			//return getListView(position, convertView, parent,(T) bean);
		}
	}

	/*----------------------------------------list adapter结束----------------------------------*/
	private abstract class LoadFailureRunnable implements Runnable {
		@Override
		public void run() {
			AlertDialog.Builder builder = new AlertDialog.Builder(
					AbstractSendListActivity.this);
			AlertDialog alert = builder.create();
			alert.setTitle(R.string.error);
			alert.setMessage(AbstractSendListActivity.this
					.getText(R.string.abstract_sendlist_activity_loadnetdata_failure));
			alert.setButton(DialogInterface.BUTTON_POSITIVE,
					AbstractSendListActivity.this
							.getText(R.string.netuser_retry),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							loadMap();
						}
					});
			alert.setButton(DialogInterface.BUTTON_NEGATIVE,
					AbstractSendListActivity.this
							.getText(android.R.string.cancel),
					new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						}
					});
			alert.show();
		}

		/**
		 * 加载地图
		 */
		public abstract void loadMap();
	}
	/*-----------------------------------------------------------------------------------------*/
}
